package com.zelin.manager.service.impl;

import com.alibaba.fastjson.JSON;
import com.zelin.manager.entity.SpecificationOptionEntity;
import com.zyg.common.utils.PageUtils;
import com.zyg.common.utils.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import com.zelin.manager.dao.TypeTemplateDao;
import com.zelin.manager.entity.TypeTemplateEntity;
import com.zelin.manager.service.TypeTemplateService;


@Service("typeTemplateService")
public class TypeTemplateServiceImpl extends ServiceImpl<TypeTemplateDao, TypeTemplateEntity> implements TypeTemplateService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private SpecificationOptionServiceImpl optionService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<TypeTemplateEntity> page = this.page(
                new Query<TypeTemplateEntity>().getPage(params),
                new QueryWrapper<TypeTemplateEntity>()
        );

        return new PageUtils(page);
    }

    //1. 根据模板id，查询品牌列表及规格列表并放到redis中
    @Override
    public TypeTemplateEntity findById(Long id) {
        //1.1 根据模板id，查询出模板对象
        TypeTemplateEntity templateEntity = this.getById(id);
        //1.2 得到模板的品牌列表字符串
        String brands = templateEntity.getBrandIds();
        //1.3 转换为List<Map>这种格式
        List<Map> brandList = JSON.parseArray(brands, Map.class);
        //1.4 查询出规格列表
        String specIds = templateEntity.getSpecIds();
        //1.4.1 转换为List<Map>格式
        List<Map> specList = JSON.parseArray(specIds, Map.class);
        //1.4.2 遍历将规格选项添加进去
        for (Map map : specList) {
            Integer specId = (Integer) map.get("id");
            List<SpecificationOptionEntity> options = optionService.list(new QueryWrapper<SpecificationOptionEntity>().eq("spec_id", specId));
            map.put("options",options);
        }
        //1.5 将品牌及规格列表放到redis中
        redisTemplate.boundHashOps("brandList").put(id+"",JSON.toJSONString(brandList));
        redisTemplate.boundHashOps("specList").put(id+"", JSON.toJSONString(specList));

        return templateEntity;
    }

}